# 任务管理接口
from flask import Blueprint, request, jsonify
from plugins import get_plugin_by_name
from core.scheduler import schedule
from models.db import MGClient

tasks_bp = Blueprint('tasks', __name__)

tasks_collection = MGClient


@tasks_bp.route("/add_task", methods=["POST"])
def add_task():
    data = request.json
    data["status"] = "active"
    print(data)
    plugin_name = data.get("plugin_name")
    try:
        plugin_obj = get_plugin_by_name(plugin_name)
        if not plugin_obj:
            return jsonify({"error": f"插件{plugin_name}, 不存在"}), 204
        # 插入数据库
        tasks_collection.exits_update_and_insert([data])
        # 更新scheduler
        schedule.update_interval(data["interval"], data["task_id"])
        return jsonify({"info": f"插入完成"}), 200
    except Exception as e:
        print(f"插入数据库发生异常：{e}")
        return jsonify({"error": "数据库异常"}), 500


@tasks_bp.route("/remove_task", methods=["POST"])
def remove_job():
    data = request.json
    task_id = data["task_id"]
    return jsonify({"info": f"移除{task_id}成功" if schedule.remove_job(task_id) else f"移除失败，{task_id}不存在"})
